package com.xd.pre.modules.security.ldap.userdetails;

import com.xd.pre.modules.sys.domain.SysUser;
import com.xd.pre.modules.sys.service.ISysUserService;
import com.xd.pre.security.LoginType;
import com.xd.pre.security.PreSecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.ldap.search.LdapUserSearch;
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;
import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;
import org.springframework.util.Assert;

import java.util.Collection;
import java.util.Set;

/**
 * 使用UserDetailsService方式实现ldap客户认证，与Manager相比，去掉了ldap账户本身的管理功能，更轻量级
 * @author tangkaifei
 */
@Slf4j
public class PreLdapUserDetailsService implements UserDetailsService {
    private final ISysUserService sysUserService;
    private final LdapUserSearch userSearch;
    private final LdapAuthoritiesPopulator authoritiesPopulator;
    private UserDetailsContextMapper userDetailsMapper = new LdapUserDetailsMapper();

    public PreLdapUserDetailsService(ISysUserService sysUserService, LdapUserSearch userSearch) {
        this(sysUserService, userSearch, new NullLdapAuthoritiesPopulator());
    }

    public PreLdapUserDetailsService(ISysUserService sysUserService, LdapUserSearch userSearch, LdapAuthoritiesPopulator authoritiesPopulator) {
        Assert.notNull(userSearch, "userSearch must not be null");
        Assert.notNull(authoritiesPopulator, "authoritiesPopulator must not be null");
        this.userSearch = userSearch;
        this.authoritiesPopulator = authoritiesPopulator;
        this.sysUserService = sysUserService;

    }

    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {

        DirContextOperations userData = userSearch.searchForUser(username);
        log.info("{}", userData);

        UserDetails userDetails = userDetailsMapper.mapUserFromContext(userData, username,
                authoritiesPopulator.getGrantedAuthorities(userData, username));

        // TODO 这里管理新ldap用户在系统的数据库映射，
//        SysUser sysUser = sysUserService.findByUserInfoName(username);
//        if (sysUser == null) {
//            // TODO 对系统中已经存在的用户，这里要增加系统中配置的权限
//
//        }

//        Set<String> dbRoles = sysUserService.findRoleIdByUserId(sysUser.getUserId());


        return new PreSecurityUser(0, userDetails.getUsername(), userDetails.getPassword(),
                userDetails.getAuthorities(), LoginType.normal);
    }

    public void setUserDetailsMapper(UserDetailsContextMapper userDetailsMapper) {
        Assert.notNull(userDetailsMapper, "userDetailsMapper must not be null");
        this.userDetailsMapper = userDetailsMapper;
    }

    private static final class NullLdapAuthoritiesPopulator implements
            LdapAuthoritiesPopulator {
        @Override
        public Collection<GrantedAuthority> getGrantedAuthorities(
                DirContextOperations userDetails, String username) {
            return AuthorityUtils.NO_AUTHORITIES;
        }
    }
}
